package com.lvmama.rhino.web.comment.comment.controller;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lvmama.rhino.pojo.comment.Enum.CommentDaysEnum;
import com.lvmama.rhino.pojo.comment.Enum.EnumForCategory;
import com.lvmama.rhino.pojo.comment.Enum.EnumForComment;
import com.lvmama.rhino.pojo.comment.entity.CategoryCommentOccupancy;
import com.lvmama.rhino.pojo.comment.entity.CommentTendency;
import com.lvmama.rhino.pojo.comment.entity.CommentTimeDistribution;
import com.lvmama.rhino.pojo.comment.query.CommentBaseQuery;
import com.lvmama.rhino.pojo.comment.query.CommentStatisticsQuery;
import com.lvmama.rhino.pojo.comment.query.CommentTendencyQuery;
import com.lvmama.rhino.pojo.comment.query.ProductCommentTypeRankQuery;
import com.lvmama.rhino.pojo.comment.response.CategoryCommentOccupancyResponse;
import com.lvmama.rhino.pojo.comment.response.CommentOccupancyResponse;
import com.lvmama.rhino.pojo.comment.response.ProductCommentTypeRankResponse;
import com.lvmama.rhino.service.comment.CommentOverviewService;
import com.lvmama.rhino.service.impl.comment.CommentOverviewServiceImpl;
import com.lvmama.rhino.service.impl.comment.RedisServiceImpl;
import com.lvmama.rhino.utils.Constants;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author:caoyong
 * @Description: 评价概述
 * @Date：2017/9/18
 */
@Controller
@RequestMapping("comment")
public class CommentOverviewController {

    private Logger log = Logger.getLogger(CommentOverviewServiceImpl.class);
    @Autowired
    private CommentOverviewService commentOverviewService;

    @Autowired
    private RedisServiceImpl redisService;
    /**
     * 查询评论趋势
     *
     * @param query 查询条件
     * @return 结果集json数组
     */
    @ResponseBody
    @RequestMapping(value = "selectCommentTendency", method = RequestMethod.GET)
    public List<CommentTendency> selectCommentTendency(CommentTendencyQuery query) {
        log.info("request selectCommentTendency start.");
        List<CommentTendency> result = new ArrayList<>();
        String commentTendencyStr;
        try {
            if (null != query.getDays() && isQueryOverview(query.getDays())) {
                log.info("selectCommentTendency redis start, query:" + query);
                String key = redisService.getKey("selectCommentTendency_" + query.getDays());
                commentTendencyStr = redisService.getObjectValue(key);
                log.info("selectCommentTendency redis end");
                if (StringUtils.isNotBlank(commentTendencyStr)) {
                    result = new Gson().fromJson(commentTendencyStr, new TypeToken<List<CommentTendency>>(){}.getType());
                } else {
                    result = queryCommentTendency(query);
                    redisService.setValueExpire(key, result, Constants.TIMEOUT);
                }
            } else {
                result = queryCommentTendency(query);
            }
        } catch (Exception e) {
            log.error("request selectCommentTendency error:" + e.getMessage());
            try {
                result = queryCommentTendency(query);
            } catch (Exception e1) {
                e1.printStackTrace();
                log.error("request selectCommentTendency mysql error:" + e1.getMessage(), e1);
            }
        }
        log.info("request selectCommentTendency end.");
        return result;
    }

    /**
     * 查询评论趋势-mysql
     * @param query
     * @return
     * @throws Exception
     */
    private List<CommentTendency> queryCommentTendency(CommentTendencyQuery query) throws Exception {
        log.info("selectCommentTendency mysql start, query:" + query);
        List<CommentTendency> result = commentOverviewService.selectCommentTendency(query);
        log.info("selectCommentTendency mysql end");
        return result;
    }

    /**
     * 查询评论占比
     *
     * @param query 查询条件
     * @return 结果集json数组
     */
    @ResponseBody
    @RequestMapping(value = "selectCommentOccupancy", method = RequestMethod.GET)
    public List<CommentOccupancyResponse> selectCommentOccupancy(CommentStatisticsQuery query) {
        log.info("queryCommentOccupancy start. query:" + query);
        List<CommentOccupancyResponse> result = new ArrayList<>();
        String commentStatisticsStr;
        try {
            if (null != query.getDays() && isQueryOverview(query.getDays())) {
                String key = redisService.getKey("selectCommentOccupancy_" + query.getDays());
                commentStatisticsStr = redisService.getObjectValue(key);
                if (StringUtils.isNotBlank(commentStatisticsStr)) {
                    result = new Gson().fromJson(commentStatisticsStr, new TypeToken<List<CommentOccupancyResponse>>() {}.getType());
                } else {
                    result = queryCommentOccupancy(query);
                    redisService.setValueExpire(key, result, Constants.TIMEOUT);
                }
            } else {
                result = queryCommentOccupancy(query);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("selectCommentOccupancy error:" + e.getMessage(), e);
            try {
                result = queryCommentOccupancy(query);
            } catch (Exception e1) {
                e1.printStackTrace();
                log.error("queryCommentOccupancy mysql requery error:" + e1.getMessage(), e1);
            }
        }
        log.info("selectCommentOccupancy end.");
        return result;
    }

    /**
     * 查询评论占比-mysql
     *
     * @param query
     * @return
     * @throws Exception
     */
    private List<CommentOccupancyResponse> queryCommentOccupancy(CommentStatisticsQuery query) throws Exception {
        log.info("comment queryCommentOccupancy start.");
        List<CommentOccupancyResponse> commentOccupancy = commentOverviewService.selectCommentStatistics(query);
        log.info("comment queryCommentOccupancy end.");
        return commentOccupancy;
    }

    /**
     * 查询点评时间分布
     *
     * @param query 查询条件
     * @return 结果集json数组
     */
    @ResponseBody
    @RequestMapping(value = "selectCommentTimeDistribution", method = RequestMethod.GET)
    public List<CommentTimeDistribution> selectCommentTimeDistribution(CommentBaseQuery query) {
        log.info("request selectCommentTimeDistribution start.");
        List<CommentTimeDistribution> distributions = null;
        String distributionsStr;
        try {
            if (null != query.getDays() && isQueryOverview(query.getDays())) {
                String key = redisService.getKey("selectCommentTimeDistribution_" + query.getDays());
                distributionsStr = redisService.getObjectValue(key);
                if (StringUtils.isNotBlank(distributionsStr)) {
                    distributions = new Gson().fromJson(distributionsStr, new TypeToken<List<CommentTimeDistribution>>() {}.getType());
                } else {
                    distributions = queryCommentTimeDistribution(query);
                    redisService.setValueExpire(key, distributions, Constants.TIMEOUT);
                }
            } else {
                distributions = queryCommentTimeDistribution(query);
            }
        } catch (Exception e) {
            log.error("request selectCommentTimeDistribution error:" + e.getMessage(), e);
            e.printStackTrace();
            try {
                distributions = queryCommentTimeDistribution(query);
            } catch (Exception e1) {
                e1.printStackTrace();
                log.error("request selectCommentTimeDistribution error:" + e1.getMessage(), e1);
            }
        }
        log.info("request selectCommentTimeDistribution end.");
        return distributions;
    }

    /**
     * mysql查询点评时间分布
     *
     * @param query
     * @return
     * @throws Exception
     */
    private List<CommentTimeDistribution> queryCommentTimeDistribution(CommentBaseQuery query) throws Exception {
        log.info("request selectCommentTimeDistribution mysql query start.");
        List<CommentTimeDistribution> distributions = commentOverviewService.selectCommentTimeDistribution(query);
        log.info("request selectCommentTimeDistribution mysql query end.");
        return distributions;
    }

    /**
     * 点评时间分布是否使用redis(全部)
     *
     * @param days
     * @return
     */
    private boolean isQueryOverview(int days) {
        if (CommentDaysEnum.YEAR.getCode() == days) {
            return true;
        }
        return false;
    }

    /**
     * 查询品类点评率占比
     *
     * @param query 查询条件
     * @return 结果集json数组
     */
    @ResponseBody
    @RequestMapping(value = "selectCategoryCommentOccupancy", method = RequestMethod.GET)
    public List<CategoryCommentOccupancyResponse> selectCategoryCommentOccupancy(CommentBaseQuery query) {
        log.info("request selectCategoryCommentOccupancy start.");
        List<CategoryCommentOccupancyResponse> result = new ArrayList<>();
        List<CategoryCommentOccupancy> occupancies = new ArrayList<>();
        Object occupanciesObj;
        try {
            if (null != query.getDays() && isQueryOverview(query.getDays())) {
                String key = redisService.getKey("selectCategoryCommentOccupancy_" + query.getDays());
                occupanciesObj = redisService.getObjectValue(key);
                if (null != occupanciesObj) {
                    String jsonStr = occupanciesObj.toString();
                    occupancies = new Gson().fromJson(jsonStr, new TypeToken<List<CategoryCommentOccupancy>>() {}.getType());
                } else {
                    occupancies = queryCategoryCommentOccupancy(query);
                    redisService.setValueExpire(key, occupancies, Constants.TIMEOUT);
                }
            } else {
                occupancies = queryCategoryCommentOccupancy(query);
            }
        } catch (Exception e) {
            log.error("request selectCategoryCommentOccupancy error:" + e.getMessage(), e);
            e.printStackTrace();
            try {
                occupancies = queryCategoryCommentOccupancy(query);
            } catch (Exception e1) {
                log.error("request selectCategoryCommentOccupancy requery error:" + e1.getMessage(), e1);
            }
        }

        try {
            if (!CollectionUtils.isEmpty(occupancies)) {
                for (int i = 0; i < occupancies.size(); i++) {
                    CategoryCommentOccupancy occupancy = occupancies.get(i);
                    CategoryCommentOccupancyResponse resp = new CategoryCommentOccupancyResponse();
                    String showName = EnumForCategory.getCategoryShowName(occupancy.getCategoryId());
                    if (StringUtils.isBlank(showName)) {
                        occupancies.remove(i);
                        i--;
                        continue;
                    }
                    resp.setCategory(showName);
                    resp.setCost(occupancy.getCount());
                    result.add(resp);
                }
            }
        } catch (Exception e) {
            log.error("request selectCategoryCommentOccupancy analysis error:" + e.getMessage(), e);
            e.printStackTrace();
        }
        log.info("request selectCategoryCommentOccupancy end.");
        return result;
    }

    /**
     * mysql查询品类点评率占比
     *
     * @param query
     * @return
     * @throws Exception
     */
    private List<CategoryCommentOccupancy> queryCategoryCommentOccupancy(CommentBaseQuery query) throws Exception {
        log.info("request queryCategoryCommentOccupancy mysql query start.");
        List<CategoryCommentOccupancy> list = commentOverviewService.selectCategoryCommentOccupancy(query);
        log.info("request queryCategoryCommentOccupancy mysql query end.");
        return list;
    }

    /**
     * 查询产品评论类型排名（差评前10）
     *
     * @param query 查询条件
     * @return 结果集json数组
     */
    @ResponseBody
    @RequestMapping(value = "selectProductCommentTypeRank", method = RequestMethod.GET)
    public List<ProductCommentTypeRankResponse> selectProductCommentTypeRank(ProductCommentTypeRankQuery query) {
        log.info("request selectProductCommentTypeRank start. query:" + query);
        List<ProductCommentTypeRankResponse> result = new ArrayList<>();
        String productCommentStr;
        try {
            if(null != query.getDays() && isQueryOverview(query.getDays())) {
                log.info("request selectProductCommentTypeRank redis query start");
                String key = redisService.getKey("selectProductCommentTypeRank_" + query.getDays());
                log.info("request selectProductCommentTypeRank redis query start");
                productCommentStr = redisService.getObjectValue(key);
                if(StringUtils.isNotBlank(productCommentStr)) {
                    result = new Gson().fromJson(productCommentStr, new TypeToken<List<ProductCommentTypeRankResponse>>() {}.getType());
                } else {
                    result = queryProductCommentTypeRank(query);
                    redisService.setValueExpire(key, result, Constants.TIMEOUT);
                }
            } else {
                result = queryProductCommentTypeRank(query);
            }
        } catch (Exception e) {
            log.error("request selectProductCommentTypeRank error:" + e.getMessage(), e);
            try {
                result = queryProductCommentTypeRank(query);
            } catch (Exception e1) {
                e1.printStackTrace();
                log.error("request selectProductCommentTypeRank requery error:" + e1.getMessage(), e1);
            }
        }
        log.info("request selectProductCommentTypeRank end.");
        return result;
    }

    /**
     * 查询产品评论类型排名（差评前10）- mysql
     *
     * @param query 查询条件
     * @return 结果集json数组
     */
    private List<ProductCommentTypeRankResponse> queryProductCommentTypeRank(ProductCommentTypeRankQuery query) throws Exception {
        log.info("request selectProductCommentTypeRank mysql query start");
        query.setCommentType(EnumForComment.negative.getValue());
        List<ProductCommentTypeRankResponse> result = commentOverviewService.selectProductCommentTypeRank(query);
        log.info("request selectProductCommentTypeRank mysql end");
        return result;
    }

    /**
     * 查询评论观点排名（消极前10）
     *
     * @param query 查询条件
     * @return 结果集json数组
     */
    @ResponseBody
    @RequestMapping(value = "selectViewpointRank", method = RequestMethod.GET)
    public List<ProductCommentTypeRankResponse> selectViewpointRank(ProductCommentTypeRankQuery query) {
        log.info("request selectViewpointRank start. query:" + query);
        List<ProductCommentTypeRankResponse> result = new ArrayList<>();
        String productRankStr;
        try {
            if (null != query.getDays() && isQueryOverview(query.getDays())) {
                log.info("comment selectViewpointRank redis query start");
                String key = redisService.getKey("selectViewpointRank_" + query.getDays());
                productRankStr = redisService.getObjectValue(key);
                log.info("comment selectViewpointRank redis query end");
                if (StringUtils.isNotBlank(productRankStr)) {
                    result = new Gson().fromJson(productRankStr, new TypeToken<List<ProductCommentTypeRankResponse>>() {}.getType());
                } else {
                    result = queryViewpointRank(query);
                    redisService.setValueExpire(key, result, Constants.TIMEOUT);
                }
            } else {
                result = queryViewpointRank(query);
            }
        } catch (Exception e) {
            log.error("request selectViewpointRank error:" + e.getMessage(), e);
            try {
                result = queryViewpointRank(query);
            } catch (Exception e1) {
                e1.printStackTrace();
                log.error("request selectViewpointRank requery error:" + e1.getMessage(), e1);
            }
        }
        log.info("request selectViewpointRank end.");
        return result;
    }

    /**
     * 查询评论观点排名（消极前10）- mysl
     * @param query
     * @return
     */
    private List<ProductCommentTypeRankResponse> queryViewpointRank(ProductCommentTypeRankQuery query) throws Exception {
        log.info("comment selectViewpointRank mysql query start");
        query.setCommentType(EnumForComment.negative.getValue());
        List<ProductCommentTypeRankResponse> result = commentOverviewService.selectViewpointRank(query);
        log.info("comment selectViewpointRank mysql query start");
        return result;
    }
}
